package models

import (
	"github.com/jinzhu/gorm"
	"kop/modules/guild/entity"
	"kop/pb"
)

func GetApplies(dB *gorm.DB, guildID int32, page, pageNum int32) []entity.Apply {

	var data []entity.Apply
	if err := dB.Where(entity.Apply{GuildID: guildID}).Order("id DESC").Limit(pageNum).Offset((page - 1) * pageNum).Find(&data).Error; err != nil {
		panic(err)
	}

	return data
}

func GetAppliesByID(dB *gorm.DB, IDs []int32) []entity.Apply {

	var data []entity.Apply
	if err := dB.Find(&data, IDs).Error; err != nil {
		panic(err)
	}

	return data
}

func CreateApply(dB *gorm.DB, role *pb.Role, guildID int32) error {

	var data = entity.Apply{
		RoleID:   role.RoleID,
		GuildID:  guildID,
		RoleName: role.Name,
		Level:    role.Level,
		Power:    role.Power,
		VIP:      role.VIP,
		Photo:    role.Photo,
	}

	return dB.Create(&data).Error
}

func FindApplyByRoleID(dB *gorm.DB, roleID, guildID int32) bool {

	var data entity.Apply
	if err := dB.Where(entity.Apply{RoleID: roleID, GuildID: guildID}).First(&data).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			panic(err)
		}
		return false
	}

	return true
}

func DelApply(dB *gorm.DB, guildID int32, IDs []int32) error {

	return dB.Where(entity.Apply{GuildID: guildID}).Delete(&entity.Apply{}, IDs).Error
}
